import {useEffect, useState} from "react";
import {Button, Image, Form, Modal, Row, message, List} from "antd";
import {ApiFindInfo} from "@/api";
import useCard from "@/hooks/useCard";
import useBoolean from "@/hooks/useBoolean";
import DndTable from "@/components/common/table/dndTable";
import UploadFile from "@/components/common/form/uploadFile";
import {CustomFormItem, InputFormItem, SelectFormItem} from "@/components/common/form/formItem";
import {columnsIndex, columnsRelevanceId, columnsSetting, columnsTitle} from "@/components/Columns";

const TYPE = 3;

export default function Cagetory() {
    const [form] = Form.useForm();
    const [visibly, on, off] = useBoolean(false);
    const [onDel, onCreateOrEdit] = useCard({});
    const [row, setRow] = useState<any>("");
    const [img, setImg] = useState("");
    const [data, setData] = useState([]);
    const [selectData, setSelectData] = useState<any[]>([]);

    const columns = [
        columnsIndex,
        columnsTitle,
        columnsRelevanceId,
        {
            title: "图片链接",
            dataIndex: "imgUrl",
            key: "imgUrl",
            render: (src: any) => <Image width={50} src={src} />,
        },
        {
            title: "关联子分类",
            dataIndex: "spare1",
            key: "spare1",
            width: 340,
            render: (val: any) => {
                const arr = String(val).split(",");
                return (
                    <List
                        itemLayout="horizontal"
                        dataSource={arr}
                        renderItem={item => {
                            const idx = selectData.findIndex(val => val.pkId == item);
                            if (idx === -1) {
                                return "";
                            }
                            return (
                                <List.Item key={item}>
                                    <div className="flr" style={{width: "100%"}}>
                                        <div>
                                            名称：
                                            {(selectData[idx].spare1 ? selectData[idx].spare1 + "-" : "") +
                                                selectData[idx].title}
                                        </div>
                                        <div>物料Id:{item}</div>
                                    </div>
                                </List.Item>
                            );
                        }}
                    />
                );
            },
        },
        {
            ...columnsSetting,
            render: (_: any, row: any) => (
                <div>
                    <Button type="primary" size="small" onClick={() => handleEdit(row)}>
                        编辑
                    </Button>

                    <Button danger onClick={() => handleDel(row)} style={{marginLeft: 20}} size="small">
                        删除
                    </Button>
                </div>
            ),
        },
    ];
    const handleEdit = (row: any) => {
        setRow(row);
        setImg(row.imgUrl);
        if (row.spare1) {
            row.spare1 = row.spare1?.split(",").map((item: string) => Number(item)) || [""];
        } else {
            delete row.spare1;
        }
        on();
        form.setFieldsValue(row);
    };
    const handleDel = (row: any) => {
        const params = [{pkId: row.pkId}];
        onDel(params, reqFindList);
    };

    const handleOk = async () => {
        try {
            const val = await form.validateFields();
            val.spare1 = val.spare1.join(",");
            if (!img) {
                return message.error("请上传图片");
            }
            let arr = [];
            if (row) {
                arr = [{...val, pkId: row.pkId, imgUrl: img, type: TYPE}];
            } else {
                arr = [{...val, imgUrl: img, type: TYPE}];
            }
            const res: any = await onCreateOrEdit(arr);
            setImg("");
            if (res) {
                reqFindList(onCancel);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const onCancel = () => {
        setRow("");
        off();
    };

    //查找列表
    const reqFindList = (callBack?: any) => {
        ApiFindInfo({type: TYPE})
            .then((res: any) => {
                setData(res.data);
                callBack && callBack();
            })
            .catch((err: any) => {
                message.error(err);
            });
    };
    const findSelect = () => {
        ApiFindInfo({type: 5})
            .then((res: any) => {
                setSelectData(res.data);
            })
            .catch((err: any) => {
                message.error(err);
            });
    };

    useEffect(() => {
        reqFindList();
        findSelect();
    }, []);

    return (
        <>
            <Row>
                <Button type="primary" onClick={on}>
                    添加Tabs
                </Button>
                &nbsp;&nbsp;
                <Button type="primary" onClick={() => onCreateOrEdit(data)}>
                    保存排序
                </Button>
            </Row>
            <DndTable style={{marginTop: 20}} setData={setData} data={data} columns={columns} />
            <Modal
                destroyOnClose
                title={`${row ? "编辑" : "添加"}快捷导航`}
                open={visibly}
                onOk={handleOk}
                onCancel={onCancel}
            >
                <Form form={form} labelAlign="left" labelCol={{span: 5}} preserve={false}>
                    <InputFormItem name="title" label="标题" required />
                    <InputFormItem name="rid" label="Id" required />
                    <SelectFormItem
                        name="spare1"
                        required
                        label="关联分类"
                        mode="multiple"
                        options={selectData.map(item => ({
                            label: item.spare1 ? item.spare1 + "-" + item.title : item.title,
                            value: item.pkId,
                        }))}
                    />
                    <CustomFormItem name="imgUrl" label="图片地址">
                        {img ? (
                            <>
                                <Image
                                    src={img}
                                    alt="avatar"
                                    style={{
                                        width: "100%",
                                        maxWidth: 300,
                                    }}
                                />
                                <div>
                                    <Button style={{marginTop: 10}} onClick={() => setImg("")} danger>
                                        删除图片
                                    </Button>
                                </div>
                            </>
                        ) : (
                            <UploadFile setImg={setImg} />
                        )}
                    </CustomFormItem>
                </Form>
            </Modal>
        </>
    );
}
